package com.ljl.user.service.impl;

import com.ljl.basic.constant.VerifyCodeConstants;
import com.ljl.basic.exception.BusinessException;
import com.ljl.basic.util.MD5Utils;
import com.ljl.basic.util.StrUtils;
import com.ljl.org.domain.Employee;
import com.ljl.user.domain.Logininfo;
import com.ljl.user.domain.User;
import com.ljl.user.dto.EmailUto;
import com.ljl.user.dto.UserDto;
import com.ljl.user.mapper.LogininfoMapper;
import com.ljl.user.mapper.UserMapper;
import com.ljl.user.service.IUserService;
import com.ljl.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/**
 * 业务实现类：
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements IUserService {
    @Autowired

    private RedisTemplate redisTemplate;
    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private JavaMailSender javaMailSender;

    @Override
    public void registerPhone(UserDto userDto) {
        String phone = userDto.getPhone();
        String phoneCode = userDto.getPhoneCode();
        String password = userDto.getPassword();
        String passwordRepeat = userDto.getPasswordRepeat();

        //1.校验
        //1.1.空值校验
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(phoneCode)
            || StringUtils.isEmpty(password) || StringUtils.isEmpty(passwordRepeat)){
            throw new BusinessException("请输入内容");
        }
        //1.2.两次密码是否相同
        if(!password.trim().equals(passwordRepeat.trim())){
            throw new BusinessException("两次密码不一致，请重新输入");
        }
        //1.3.验证码是否过期
        Object redisCode = redisTemplate.opsForValue().get(VerifyCodeConstants.REGISTER_PREFIX + phone);
        if(redisCode == null){
            throw new BusinessException("验证码已经过期请重新获取！");
        }
        //1.4.验证码是否正确
        String codeTmp = redisCode.toString().split(":")[0];
        if (!codeTmp.equals(phoneCode)){
            throw new BusinessException("验证码输入错误");
        }

        //2.保存数据
        //2.1.先保存t_logininfo
        User user = userDto2User(userDto);
        Logininfo logininfo = user2Logininfo(user);

        logininfoMapper.save(logininfo);
        user.setLogininfo_id(logininfo.getId());
        userMapper.save(user);
    }

    @Override
    public void registerEmail(EmailUto emailUto) throws MessagingException {
        String email = emailUto.getEmail();
        String emailPassword = emailUto.getEmailPassword();
        String emailPasswordRepeat = emailUto.getEmailPasswordRepeat();
        // 判断空值
        if (StringUtils.isEmpty(email) || StringUtils.isEmpty(emailPassword)
                || StringUtils.isEmpty(emailPasswordRepeat)){
            throw new BusinessException("请输入内容");
        }
        // 校验密码是否一致
        if(!emailPassword.trim().equals(emailPasswordRepeat.trim())){
            throw new BusinessException("两次密码不一致，请重新输入");
        }
        // 校验邮箱判断是否注册过
        User findUser = userMapper.findByEmail(email);
        if(findUser != null){
            throw new BusinessException("你的邮箱已经注册过，如果忘记密码请联系管理员");
        }

        User user = emailUto2User(emailUto);
        // 1.添加logininfo
        Logininfo logininfo = email2Logininfo(user);
        logininfoMapper.save(logininfo);
        user.setLogininfo_id(logininfo.getId());
        userMapper.save(user);

        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        //发送复杂邮件的工具类
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,"utf-8");
        helper.setFrom("1214171913@qq.com");
        helper.setSubject("店铺激活邮件");
        helper.setText("<h1>你的账号注册成功!!!</h1>" +
                "<a href='http://localhost:8080/user/active/"+user.getId()+"'>点击该链接去往登陆</a>",true);
        //收件人
        helper.setTo(email);
        javaMailSender.send(mimeMessage);
    }

    private User emailUto2User(EmailUto emailUto) {
        User user = new User();
        user.setUsername(emailUto.getEmail());
        user.setEmail(emailUto.getEmail());

        String salt = StrUtils.getComplexRandomString(32);
        user.setSalt(salt);
        String md5 = MD5Utils.encrypByMd5(emailUto.getEmailPassword() + salt);
        user.setPassword(md5);
        user.setState(0);
        return user;
    }

    private Logininfo email2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);
        logininfo.setDisable(false);
        return logininfo;
    }


    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);
        return logininfo;

    }

    private User userDto2User(UserDto userDto) {
        User user = new User();
        user.setUsername(userDto.getPhone());
        user.setPhone(userDto.getPhone());

        String salt = StrUtils.getComplexRandomString(32);
        user.setSalt(salt);
        String md5 = MD5Utils.encrypByMd5(userDto.getPassword() + salt);
        user.setPassword(md5);
        return user;
    }

    @Override
    public void del(Long id) {
        User user = userMapper.findById(id);
        logininfoMapper.del(user.getLogininfo_id());
        super.del(id);
    }

    @Override
    public void update(User user) {
        String salt = StrUtils.getComplexRandomString(32);
        user.setSalt(salt);
        String md5 = MD5Utils.encrypByMd5(salt + user.getPassword());
        user.setPassword(md5);

        Long logininfo_id = userMapper.findById(user.getId()).getLogininfo_id();
        Logininfo logininfo = user2Logininfo(user);
        logininfo.setId(logininfo_id);
        logininfoMapper.update(logininfo);
        super.update(user);
    }
}
